<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card>
      <!-- 带搜索功能的input     -->
      <el-input
        placeholder="请输入内容"
        style="width: 400px"
        v-model="queryInfo.query"
      >
        <el-button
          slot="append"
          icon="el-icon-search"
          @click="searchUser"
        ></el-button>
      </el-input>
      <!-- 添加用户按钮 -->
      <el-button type="primary" class="addBtn" @click="showAddUser"
        >添加用户</el-button
      >

      <!-- 表格 -->
      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#409eff"
              @change="changeStatus(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="small"
              @click="showEditUser(scope.row)"
            >
            </el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="deleteUser(scope.row)"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <!-- 设置角色 -->
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="small"
                @click="getRolesList(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 修改用户信息对话框 -->
      <el-dialog
        title="修改用户信息"
        :visible.sync="editDialogVisible"
        width="50%"
      >
        <!-- 表单 -->
        <el-form :model="editFrom" ref="editFromRef" label-width="100px">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editFrom.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editFrom.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserData">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配用户角色对话框 -->
      <el-dialog
        title="分配用户角色"
        :visible.sync="rolesDialogVisible"
        width="50%"
      >
        <!-- select选择器 -->
        <el-select v-model="roleId" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :value="item.id"
            :label="item.roleName"
          >
          </el-option>
        </el-select>
        <span slot="footer" class="dialog-footer">
          <el-button @click="rolesDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="userRulesData">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 添加用户对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addFromClosed"
      >
        <!-- 表单 -->
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="100px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号码">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUserData">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "Users",
  data() {
    return {
      // 用户列表
      userList: [],
      // 查询用户的信息
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 10,
      },
      // 总数据
      total: 0,
      // 修改用户模块
      editDialogVisible: false,
      editFrom: {
        id: "",
        mobile: "",
        email: "",
      },
      // 分配角色信息
      rolesList: [],
      roleId: "",
      roleUserId: "",
      rolesDialogVisible: false,
      props: {
        expandTrigger: "hover",
      },

      // 添加用户模块
      addDialogVisible: false,
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 5, max: 8, message: "长度在 5 到 8 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });

      if (res.meta.status !== 200)
        return this.message.error("获取用户信息失败");

      this.userList = res.data.users;
      this.total = res.data.total;
    },
    // 改变状态
    async changeStatus(row) {
      const { data: res } = await this.$http.put(
        `users/${row.id}/state/${row.mg_state}`
      );
      if (res.meta.status !== 200) return this.$message.error("修改状态失败");
    },
    // 分页大小发生改变
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    // 当前页码发生改变
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    // 搜索词搜索
    searchUser() {
      this.getUserList();
    },
    // 打开修改用户信息对话框
    showEditUser(row) {
      this.editDialogVisible = true;

      this.editFrom.id = row.id;
      this.editFrom.email = row.email;
      this.editFrom.mobile = row.mobile;
    },
    // 确认修改用户信息
    async editUserData() {
      const { data: res } = await this.$http.put(`users/${this.editFrom.id}`, {
        email: this.editFrom.email,
        mobile: this.editFrom.mobile,
      });

      if (res.meta.status !== 200) return this.$message.error("修改失败");

      this.$message.success("修改成功");
      this.editDialogVisible = false;
      this.getUserList();
    },
    // 删除用户
    async deleteUser(row) {
      const confirmStr = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      if (confirmStr !== "confirm") return this.$message.info("取消了删除操作");

      const { data: res } = await this.$http.delete(`users/${row.id}`);

      if (res.meta.status !== 200) return this.$essage.error("删除失败");

      this.$message.success("删除成功");
      this.getUserList();
    },
    // 获取角色列表信息
    async getRolesList(row) {
      this.rolesDialogVisible = true;
      this.roleUserId = row.id;

      // 获取角色列表
      const { data: res } = await this.$http.get("roles");

      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表失败");
      this.rolesList = res.data;
    },
    // 分配用户角色
    async userRulesData() {
      const { data: res } = await this.$http.put(
        `users/${this.roleUserId}/role`,
        { rid: this.roleId }
      );
      if (res.meta.status !== 200) return this.$message.error("设置角色失败");

      this.$message.success("设置角色成功");
      this.rolesDialogVisible = false;
      this.getUserList();
    },
    // 开启添加用户对话框
    showAddUser() {
      this.addDialogVisible = true;
    },
    // 添加用户
    addUserData() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请填用户名和密码");
        const { data: res } = await this.$http.post("users", {
          username: this.addForm.username,
          password: this.addForm.password,
          email: this.addForm.email,
          mobile: this.addForm.mobile,
        });

        console.log(res);
        if (res.meta.status !== 201) return this.$message.error("用户创建失败");

        this.$message.success("用户创建成功");
        this.getUserList();
        this.addDialogVisible = false;
      });
    },
    // 关闭添加用户对话框
    addFromClosed() {
      this.$refs.addFormRef.resetFields();
    },
  },
};
</script>

<style scoped>
.addBtn {
  margin-left: 25px;
}
</style>